package com.example.communist_app_api.controller.web;

import com.example.communist_app_api.db.pojoDto.OrganizationalStructureDTO;
import com.example.communist_app_api.db.pojo.User;
import com.example.communist_app_api.db.pojoDto.Organization;
import com.example.communist_app_api.service.*;
import com.example.communist_app_api.util.JwtUtils;
import com.example.communist_app_api.util.R;
import com.example.communist_app_api.vo.web.req.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Brother Sheng Editor
 * @version 1.0
 * Create by 2023/3/15 10:52
 */
@RestController
@RequestMapping("/structure")
@Api("组织架构控制器")
public class OrganizationalStructureController {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;


    @PostMapping("/createPartyCommittee")
    @ApiOperation("新建党委")
    public R createPartyCommittee(@RequestBody CreatePartyCommitteeReq req){
        //只允许一个党委存在，查询parentId是否有为0的存在，有的话就禁止添加
        Organization organization = organizationService.getParentIdIsZero();
        if (organization != null) {
            return R.error("新增失败，已经存在"+organization.getOrganizationName());
        }
        //新增党委
        Organization createOrganization = new Organization();
        createOrganization.setOrganizationName(req.getOrganizationName());
        createOrganization.setAddress(req.getAddress());

        Boolean createFlag = organizationService.createNewPartyCommittee(createOrganization);

        if (createFlag) {
            return R.ok("新增成功");
        }else {
            return R.error("新增失败");
        }
    }

    @PostMapping("/createGeneralPartyBranch")
    @ApiOperation("新建党总支")
    public R createGeneralPartyBranch(@RequestBody CreateGeneralPartyBranchReq req){
        //新增党总支
        Organization createOrganization = new Organization();
        createOrganization.setOrganizationName(req.getOrganizationName());
        createOrganization.setAddress(req.getAddress());
        createOrganization.setParentId(req.getParentId());

        //查询是否重复新增
        Organization organizationByOrganizationName = organizationService.getOrganizationByOrganizationName(req.getOrganizationName());

        if (organizationByOrganizationName != null) {
            return R.error("已存在该党总支"+organizationByOrganizationName.getOrganizationName());
        }

        Boolean createFlag = organizationService.createGeneralPartyBranch(createOrganization);

        if (createFlag) {
            return R.ok("新增成功");
        }else {
            return R.error("新增失败");
        }
    }

    @PostMapping("/createPartyBranch")
    @ApiOperation("新建党支部")
    public R createGeneralPartyBranch(@RequestBody CreatePartyBranchReq req){

        //新增党总支
        Organization createOrganization = new Organization();
        createOrganization.setOrganizationName(req.getOrganizationName());
        createOrganization.setAddress(req.getAddress());
        createOrganization.setParentId(req.getParentId());

        //查询是否重复新增
        Organization organizationByOrganizationName = organizationService.getOrganizationByOrganizationName(req.getOrganizationName());

        if (organizationByOrganizationName != null) {
            return R.error("已存在该党支部"+organizationByOrganizationName.getOrganizationName());
        }

        Boolean createFlag = organizationService.createPartyBranch(createOrganization);

        if (createFlag) {
            return R.ok("新增成功");
        }else {
            return R.error("新增失败");
        }
    }

    @PostMapping("/show")
    @ApiOperation("查看组织架构")
    public R showOrganizationStructure(@RequestBody ShowOrganizationStructureReq req, HttpServletRequest httpServletRequest){
        //通过httpServletRequest获取当前操作的userId
        Integer userId = getUserIdByWebToken(httpServletRequest);
        Organization organization = new Organization();
        organization.setOrganizationName(req.getOrganizationName());

        PageInfo<OrganizationalStructureDTO> pageInfo  = organizationService.selectAllOrganization(organization,req.getPageNum(),req.getPageSize(),userId);
        return R.ok("查询成功").put("pageInfo",pageInfo);
    }

    //系统管理员任命总支书记
    @PostMapping("/assignSecretaryOfTheGeneralBranch")
    @ApiOperation("任命总支书记")
    //userIdBySecretaryOfTheGeneralBranch总支书记的Id
    public R assignSecretaryOfTheGeneralBranch(@RequestParam("userIdBySecretaryOfTheGeneralBranch") Integer userIdBySecretaryOfTheGeneralBranch,
                                               HttpServletRequest httpServletRequest,@RequestParam("organizationId") Integer organizationId){
        //通过httpServletRequest获取当前操作的userId
        Integer userId = getUserIdByWebToken(httpServletRequest);
        organizationService.assignSecretaryOfTheGeneralBranch(userIdBySecretaryOfTheGeneralBranch,userId,organizationId);
        return R.ok("任命成功");
    }

        //任命总支下面的党支部书记过程
        @PostMapping("/showAllUser")
        @ApiOperation("显示可选择的人")
        //用于提供人名,进行人员更改任命
        public R showAllUserByGeneralBranch(@RequestParam("organizationIdBySelect") Integer organizationIdBySelect){
            //对于已经任命的人员进行组织关系的转移
            List<User> userList = userOrganizationService.getAllUserByOrganizationIdBySelect(organizationIdBySelect);
            return R.ok("显示成功").put("userList",userList);
        }

    /**
     *
     * @param userIdBySelect 被总支书记选中的用户Id
     * @param organizationId 要去任命的组织Id，简单的说，党总支书记任命这个党支部的书记是谁
     * @param httpServletRequest
     * @return
     */

        //支部书记的任命(相当于在组织架构页面进行分配角色支部书记的操作)
        @PostMapping("/assignBranchSecretary")
        @ApiOperation("任命支部书记")
        public R assignBranchSecretary(@RequestParam("userIdBySelect") Integer userIdBySelect ,
                                       @RequestParam("organizationId") Integer organizationId,
                                       HttpServletRequest httpServletRequest){
            Integer userIdByWebToken = getUserIdByWebToken(httpServletRequest);
            organizationService.assignBranchSecretary(userIdBySelect,userIdByWebToken,organizationId);
            return R.ok("任命成功");
        }

        //修改党总支，党支部名称，地址
        @PostMapping("/update")
        @ApiOperation("修改指定组织的信息")
        public R updateSelectOrganizationMessage(@RequestBody UpdateSelectOrganizationMessageReq req,
                                                 HttpServletRequest httpServletRequest){
            Integer userIdByWebToken = getUserIdByWebToken(httpServletRequest);
            Organization organization = new Organization();
            organization.setId(req.getId());
            organization.setOrganizationName(req.getOrganizationName());
            organization.setAddress(req.getAddress());
            organizationService.updateOrganizationMessage(organization,userIdByWebToken);
            return R.ok("修改成功");
        }

        //删除党支部
        @PostMapping("/deletedOrganization")
        @ApiOperation("删除党支部")
        public R deletedOrganization(@RequestParam("organizationId") Integer organizationId,
                                     HttpServletRequest httpServletRequest){
            Integer userIdByWebToken = getUserIdByWebToken(httpServletRequest);
            //删除前判断user_organization表中该组织是否还存在没有转组织关系的人,理论上党支部已经没有人
            Integer userNum = userOrganizationService.getUserNumInOrganizationByOrganizationId(organizationId);
            if (userNum == 0) {
                organizationService.deletedPartyBranch(organizationId,userIdByWebToken);
            }else {
                return R.error("删除失败，党支部内还存在未转出组织的人，共："+userNum+"人。请联系该党支部书记或相关人员进行组织关系的转移，后再进行删除操作");
            }
            return R.ok("删除党支部成功");
        }

        //关系转移
        @PostMapping("/transformRelationship")
        @ApiOperation("组织转移")
        public R transformRelationship(@RequestBody TransformRelationshipReq req){
            Integer userId = req.getUserId();
            Integer organizationId = req.getOrganizationId();
            userOrganizationService.transformRelationshipByUserIdAndOrganizationId(userId,organizationId);
            return R.ok("转移成功");
        }



        private Integer getUserIdByWebToken(HttpServletRequest httpServletRequest){
            //在web端用username做加密的token
            String token = httpServletRequest.getHeader("token");
            String username = JwtUtils.parseJWT(token).getSubject();
            Integer userId = userService.getUserInfo(username).getId();
            return userId;
        }


}
